
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>列表过滤</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
    <div id="root">
        <ul>
            <h2>人员列表</h2>
            <input type="text" placeholder="请输入名字" v-model="inputValue"/>
            <button @click="updataMei">更新周冬梅信息</button>
            <button @click="sortType = 2">年龄升序</button>
            <button @click="sortType = 1">年龄降序</button>
            <button @click="sortType = 0">原顺序</button>
            <!-- 遍历数组 -->
            <!-- <li v-for="person in persons" :key="person.id">{{person.name}}-{{person.age}}</li> -->
            <!-- 多个参数最好加个小括号 -->
            <li v-for="(p,index) in nullPerson" :key="p.id" >
                {{index}} -- {{p.name}} -- {{p.age}}
            </li>
        </ul>
    </div>
</body>
<script type="text/javascript">
    Vue.config.productionTip = false

    // 用Watch实现
    //#region 
    // new Vue({
    //     el:'#root',
    //     data:{
    //         persons:[
    //             {id:'001',name:'周冬梅 ',age:18,sex:'女'},
    //             {id:'002',name:'周冬雨',age:19,sex:'女'},
    //             {id:'003',name:'周杰伦',age:20,sex:'男'},
    //             {id:'004',name:'温兆伦',age:22,sex:'男'}
    //         ],
    //         inputValue:'',
    //         nullPerson:[]   
    //     },watch:{
    //         inputValue:{
    //             immediate:true,
    //             handler(val){
    //                 this.nullPerson = this.persons.filter((p)=>{
    //                 return p.name.indexOf(val) !== -1
    //             })
    //         }
    //         }
    //     }
    // })
    //#endregion
    
    //用Comp
    new Vue({
        el:'#root',
        data:{
            persons:[
                {id:'001',name:'周冬梅 ',age:17,sex:'女'},
                {id:'002',name:'周冬雨',age:22,sex:'女'},
                {id:'003',name:'周杰伦',age:28,sex:'男'},
                {id:'004',name:'温兆伦',age:21,sex:'男'}  
            ],
            inputValue:'',
            sortType: 0 // 0 原顺序 1降序 2升序 
      },
      computed:{
        nullPerson(){
            const arr= this.persons.filter((p)=>{
                return p.name.indexOf(this.inputValue) !== -1
            })
            //判断一下是否排序
            if(this.sortType){
                arr.sort((p1,p2)=>{
                    //函数体
                    return this.sortType == 1 ? p2.age-p1.age : p1.age - p2.age
                })
            }
            return arr
        }
        },methods: {
            updataMei(){
                this.persons[0].name="若风"
                this.persons[0].age=30 
            }
        },
    })
</script>
</html>